﻿using Inovout.Account.Web.Filters;
using Inovout.Account.Web.Models;
using Inovout.EntityPropertyValidation;
using Inovout.Memberships;
using Inovout.Memberships.Models;
using Inovout.Memberships.Services;
using Inovout.Models;
using Inovout.People.Memberships.Services;
using Inovout.People.Models;
using Inovout.RedictUrls;
using Inovout.Runtime;
using Inovout.Services;
using Inovout.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Inovout.Account.Web.Controllers
{
    [AllowAnonymous]
    public class MembershipUserController : BaseController
    {
        private IRedictUrlService redictUrlService;
        private IMembershipUserService membershipUserService;

        public MembershipUserController(IRedictUrlService redictUrlService,
            IPersonMembershipService personMembershipService,
            IMembershipUserService membershipUserService)
        {
            this.redictUrlService = redictUrlService;
            this.membershipUserService = membershipUserService;
        }

       // public ActionResult Activate(string email, string linkText, string message, string returnUrl)
        public ActionResult Activate(string email, int membershipUser, string linkText, string message)
        {
            ViewBag.Email = email;
            ViewBag.Message = message;
            ViewBag.MembershipUser = membershipUser;
        
            if (!string.IsNullOrEmpty(linkText))
            {
                ViewBag.LinkText = linkText;
            }
            else
            {
                ViewBag.LinkText = "没收到？再次发送。";
            }
            return View();
        }

        public ActionResult LoginEmail(string email)
        {
            string emailDomain = email.Split('@')[1].ToString().ToLower();
            string emailUrl = "http://mail." + emailDomain;
            return Redirect(emailUrl);
        }

        public ActionResult SendEmail(string email, int membershipUser, string message)
        {

            SendEmailProcess(email, membershipUser);
            string linkText = "邮件已发送。";
            return RedirectToAction("Activate", "MembershipUser", new { email = email, membershipUser = membershipUser, linkText = linkText, message = message });
        }

        private void SendEmailProcess(string email, int membershipUser)
        {
           // RedirctUrl entity = ComponentRegistry.Resolve<IRepositoryService<RedirctUrl>>().FindById(redirctUrl);
         
            RedirctUrl entity = ComponentRegistry.Resolve<IRedictUrlService>().FindByOrginalUrlByMembershipUserId(membershipUser);   
                 //刷新验证有效时间
            Inovout.ComponentRegistry.Resolve<IRedictUrlService>().Save(entity);

            string subject = "3Cloud 新用户激活邮件";
            string plate = @"亲爱的$(email)："
                + Environment.NewLine
                + Environment.NewLine + "感谢您申请注册三宝云！请点击链接激活账户："
                + Environment.NewLine + "$(url)"
                + Environment.NewLine
                + Environment.NewLine + "如果上述链接点击无效，请将该网页地址复制到浏览器地址栏中打开。"
                + Environment.NewLine
                + Environment.NewLine + "如果您没有申请注册三宝云，请忽略此邮件。"
                + Environment.NewLine
                + Environment.NewLine + "---------------------------------------------------------------------------------------------------------"
                + Environment.NewLine
                + Environment.NewLine + "本邮件由系统自动发出，请勿回复。";

            Dictionary<string, string> contents = new Dictionary<string, string>();
            contents.Add("email", email);
            contents.Add("url", entity.ActionUrl);
            Inovout.ComponentRegistry.Resolve<IRedictUrlService>().SendMail(plate, contents, subject);
        }

        [ProtectedAction]
        public ActionResult ActivateUser()
        {
            string email = Request.QueryString["Email"];
            string id = Request.QueryString["MembershipUser"];
            MembershipUser memberUser = (MembershipUser)membershipUserService.FindById(Convert.ToInt32(id));
            if (memberUser != null && memberUser.Status == MembershipUserStatus.Activate)
            {
                return RedirectToAction("ActivateFailed", "MembershipUser", new { message = "验证重复" });
            }
            else
            {
                memberUser.Status = MembershipUserStatus.Activate;
                Inovout.ComponentRegistry.Resolve<IRepositoryService<MembershipUser>>().Save(memberUser);
                UpdateEntityPropertyValidationResult(((Inovout.Memberships.Models.Membership)memberUser.Membership).Id);
                ViewBag.ReturnUrl = Request.QueryString["returnUrl"];
                return View("ActivateSuccess");
            }
        }

       private static void UpdateEntityPropertyValidationResult(int  id)
       {
            Inovout.Memberships.Models.Membership membership = Inovout.ComponentRegistry.Resolve<MembershipService>().FindById(id);
            string propertyName = "Email";
            string type = membership.MembershipType.ToString();
            EntityPropertyValidationResult validationResult = Inovout.ComponentRegistry.Resolve<IEntityPropertyValidationResultService>().FindByEntiry(membership, type, propertyName);
            validationResult.IsValid = true;
            validationResult.ValidatedTime = System.DateTime.Now;
            Inovout.ComponentRegistry.Resolve<IRepositoryService<EntityPropertyValidationResult>>().Save(validationResult);
        }

        public ActionResult ActivateFailed(string message)
        {
            string email = Request.QueryString["Email"];
            ViewBag.Email = email;
            ViewBag.Message = message;
            return View();
        }
    }
}